//
//  LockView.swift
//  LiteAccount
//
//  Created by 刘伟 on 2017/6/5.
//  Copyright © 2017年 刘伟. All rights reserved.
//

import UIKit

protocol LockViewDelegate: class {
    func didFinished(_ isSuccess: Bool, title: String, message: String, password:[Int])
}

class LockView: UIView {
    // 代理协议
    weak var delegate: LockViewDelegate?
    var btnArray = [UIButton]()
    // 被选中的按钮的 tag 数组
    var selectedBtnTagArray = [Int]()
    var gesturePoint = CGPoint()
    // 按钮宽高
    let btnWH:CGFloat = 50
    let btnNormalImg = UIImage(named: "lockview_normal")
    let btnSelectedImg =  UIImage(named: "lockview_selected")
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .la_app
        initView()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func draw(_ rect: CGRect) {
        print("执行drawRect")
        let context = UIGraphicsGetCurrentContext() //获取画笔上下文
        
        var i = 0
        for tag in selectedBtnTagArray {
            if (0 == i) {
                //开始画线,设置直线的起点坐标
                context?.move(to: CGPoint(x: btnArray[tag].center.x, y: btnArray[tag].center.y))
            } else {
                //画直线,设置直线的终点坐标
                context?.addLine(to: CGPoint(x: btnArray[tag].center.x, y: btnArray[tag].center.y))
            }
            i = i+1
        }
        
        //如果有选中的节点，就取 跟着 手指的滑动 画线
        if (selectedBtnTagArray.count > 0) {
            // 移除最后一条多余的线，
            if gesturePoint != CGPoint.zero {
                context?.addLine(to: CGPoint(x: gesturePoint.x, y: gesturePoint.y))
            }
        }
        
        context?.setLineWidth(4)      //设置画笔宽度
        context?.setLineJoin(.round)   //两个线相交点 平滑处理
        context?.setLineCap(.round)    //设置线条两端的样式为圆角
        context?.setStrokeColor(UIColor(red:0.57, green:0.91, blue:1.00, alpha:1.00).cgColor)
        context?.strokePath()            // //对线条进行渲染
    }
    
    // MARK: - Override
    // 当手指接触屏幕时，就会调用touchesBegan:withEvent方法；
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        print("执行touchesBegan")
        selectedBtnTagArray.removeAll()
        touchesChange(touches)
    }
    
    //当手指在屏幕上移动时，调用touchesMoved:withEvent方法；
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        touchesChange(touches)
    }
    
    //当触摸被取消（比如触摸过程中被来电打断），就会调用touchesCancelled:withEvent方法。
    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
        
    }
    //当手指离开屏幕时，就会调用touchesEnded:withEvent方法；
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        print("执行touchesEnded")
        var alertTitle =  "请设置正确的手势"
        var alertMessage = "手势密码不能少于4个"
        var isSuccess = false
        
        if selectedBtnTagArray.count >= 4 {
            alertTitle =  "手势密码设置成功"
            isSuccess = true
            alertMessage = ""
        }
        
        delegate?.didFinished(isSuccess, title: alertTitle, message: alertMessage, password: selectedBtnTagArray)
        
        gesturePoint = CGPoint.zero;
        self.setNeedsDisplay()
    }

    
    // 初始化锁屏界面
    fileprivate func initView() {
        // 按钮间距
        let btnSpace = ( SCREEN_WIDTH - 3 * btnWH ) / 4
        for i in 0 ... 8 {
            let row = i / 3
            let col = i % 3
            let btnX = btnSpace + ( btnWH + btnSpace ) * CGFloat(col)
            let btnY = btnSpace + (btnWH + btnSpace) * CGFloat(row)
            
            let btn = UIButton(frame: CGRect(x: btnX, y: btnY, width: btnWH, height: btnWH))
            btn.tag = i
            btn.isUserInteractionEnabled = false
            btn.setImage(btnNormalImg, for: .normal)
            self.addSubview(btn)
            btnArray.append(btn)
        }
    }
    
    fileprivate func touchesChange(_ touches: Set<UITouch>) {
        //获取 触摸对象 ,触摸对象的位置坐标来实现
        gesturePoint = touches.first!.location(in: self)
        
        for btn in btnArray {
            //判断 手指的坐标 是否在 button的坐标里
            if !selectedBtnTagArray.contains(btn.tag) && btn.frame.contains(gesturePoint) {
                //处理跳跃连线
                var lineCenterPoint:CGPoint = CGPoint()
                
                if selectedBtnTagArray.count > 0 {
                    lineCenterPoint = centerPoint(btn.frame.origin, endPoint: btnArray[selectedBtnTagArray.last!].frame.origin)
                }
                
                //保存中间跳跃 过的节点
                for btn in btnArray {
                    if  !selectedBtnTagArray.contains(btn.tag) && btn.frame.contains(lineCenterPoint)  {
                        btn.setImage(btnSelectedImg, for: UIControlState.normal)
                        selectedBtnTagArray.append(btn.tag)
                    }
                }
                
                //保存划过的按钮的tag
                selectedBtnTagArray.append(btn.tag)
                btn.setImage(btnSelectedImg, for: UIControlState.normal)
            }
        }
        
        //setNeedsDisplay会自动调用drawRect方法 进行画线
        self.setNeedsDisplay()
    }
    
    //计算2个节点中心的坐标
    fileprivate func centerPoint(_ startPoint: CGPoint, endPoint:CGPoint) -> CGPoint {
        let rightPoint = startPoint.x > endPoint.x ? startPoint.x : endPoint.x
        let leftPoint = startPoint.x < endPoint.x ? startPoint.x : endPoint.x
        
        let topPoint = startPoint.y > endPoint.y ? startPoint.y : endPoint.y
        let bottomPoint = startPoint.y < endPoint.y ? startPoint.y : endPoint.y
        
        //x坐标： leftPoint +（rightPoint-leftPoint)/2 = (rightPoint+leftPoint)/2
        return CGPoint(x: (rightPoint + leftPoint)/2 + btnWH/2, y: (topPoint + bottomPoint)/2 + btnWH/2);
    }
    
    func reset() {
        selectedBtnTagArray.removeAll()
        for btn in btnArray {
            btn.setImage(btnNormalImg, for: UIControlState.normal)
        }
        self.setNeedsDisplay()
    }
    
}
